<template>
	<view class="base-picker-component">
		<uv-picker
			ref="basePicker"
			:columns="columns"
			:keyName="columnName"
			@change="change"
			@cancel="cancel"
			@confirm="confirm"
		/>
	</view>
</template>

<script>
export default {
	props: {
		list: Array,
		columnName: {
			type: String,
			default: 'text'
		},
		childName: {
			type: String,
			default: 'children'
		}
	},
	watch: {
		list (data) {
			const columns = JSON.parse(JSON.stringify(data))
			const columnNums = []
			columns.forEach((item, index) => {
				if (index === 0) {
					columnNums.push(columns)
				}
				const children = item[this.childName] || []
				if (Array.isArray(children) && children.length > 0) {
					item[this.childName] = children.map((subs, idx) => {
						const objValues = typeof subs !== 'object'
							? { [this.columnName]: subs }
							: { ...subs, [this.columnName]: subs[this.columnName] }
						const lastChildren = objValues[this.childName] || []
						if (Array.isArray(lastChildren) && lastChildren.length > 0) {
							objValues[this.childName] = lastChildren.map((lasts, i) => {
								return typeof lasts !== 'object'
									? { [this.columnName]: lasts }
									: { ...lasts, [this.columnName]: lasts[this.columnName] }
							})
							if (index === 0 && idx === 0) {
								columnNums.push(objValues[this.childName])
							}
						}
						return objValues
					})
					if (index === 0) {
						columnNums.push(item[this.childName])
					}
				}
			})
			this.columns = [
				...columnNums
			]
			this.$nextTick(() => {
				this.$refs.basePicker.setIndexs(new Array(columnNums.length).fill(0), true)
			})
		}
	},
	data () {
		return {
			columns: []
		}
	},
	methods: {
		change (e) {
			const { columnIndex, index, value, picker = this.$refs.basePicker } = e
			if (columnIndex < value.length - 1) {
				const nextColumnIndex = columnIndex + 1
				const children = value[columnIndex][this.childName]
				switch (columnIndex) {
					case 0: {
						picker.setColumnValues(nextColumnIndex, children)
						if (nextColumnIndex < value.length - 1) {
							const lastColumnIndex = nextColumnIndex + 1
							picker.setColumnValues(lastColumnIndex, children[0][this.childName])
						}
						break
					}
					case 1: {
						picker.setColumnValues(nextColumnIndex, children)
						break
					}
				}
			}
		},
		open () {
			this.$refs.basePicker.open()
		},
		close () {
			this.$refs.basePicker.close()
		},
		cancel () {
			this.close()
		},
		confirm (e) {
			this.close()
			this.$emit('confirm', e.value)
		}
	}
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>